/**
 * Aibton.com Inc.
 * Copyright (c) 2004-2017 All Rights Reserved.
 */
package com.aibton.mybatis.share.utils;

import com.aibton.mybatis.share.entity.ShareData;
import com.aibton.mybatis.share.exception.MybatisShareException;

/**
 * @author huzhihui
 * @version v 0.1 2017/6/2 23:01 huzhihui Exp $$
 */
public class MybatisShareThreadLocalHolder {

    /**
     * 上下文线程变量
     */
    private static ThreadLocal<ShareData> threadLocal = new ThreadLocal<ShareData>() {
        @Override
        protected ShareData initialValue() {
            return new ShareData();
        }
    };

    /**
     * 获取分表bean配置对象
     * @return
     */
    public static ShareData getShareDate() {
        return threadLocal.get();
    }

    /**
     * 设置是否允许分表
     * @param value
     */
    public static void setAllowMybatisShare(Boolean value) {
        ShareData shareData = threadLocal.get();
        shareData.setAllowShare(value);
        threadLocal.set(shareData);
    }

    /**
     * 获取是否允许分表
     * @return
     */
    public static Boolean getAllowMybatisShare() {
        return threadLocal.get().getAllowShare();
    }

    /**
     * 设置分表后缀，优先级最低
     * @param shareTableSuffix
     */
    public static void setShareTableSuffix(String shareTableSuffix) {
        if (null == shareTableSuffix || shareTableSuffix.trim().equals("")) {
            throw new MybatisShareException("设置分表后缀失败，请检查分表后缀");
        }
        ShareData shareData = threadLocal.get();
        shareData.setShareTableSuffix(shareTableSuffix);
        threadLocal.set(shareData);
    }

    /**
     * 获取分表后缀，优先级最低
     * @return
     */
    public static String getShareTableSuffix() {
        return threadLocal.get().getShareTableSuffix();
    }

    /**
     * 设置分表后缀，优先级最高
     * @param supperShareTableSuffix
     */
    public static void setSupperShareTableSuffix(String supperShareTableSuffix) {
        if (null == supperShareTableSuffix || supperShareTableSuffix.trim().equals("")) {
            throw new MybatisShareException("设置分表后缀失败，请检查分表后缀");
        }
        ShareData shareData = threadLocal.get();
        shareData.setSupperShareTableSuffix(supperShareTableSuffix);
        threadLocal.set(shareData);
    }

    /**
     * 获取分表后缀，优先级最高
     * @return
     */
    public static String getSupperShareTableSuffix() {
        return threadLocal.get().getSupperShareTableSuffix();
    }

    /**
     * 清空分表信息
     */
    public static void clear() {
        threadLocal.set(new ShareData());
    }
}
